import { ArrayMethods } from "./arr";

export function obServer(data) {
  if (!data || typeof data !== "object") return data;
  return new ObServer(data);
}

function defineReactive(data, key, value) {
  //递归劫持
  obServer(value);
  Object.defineProperty(data, key, {
    get() {
      // console.log(`触发了get方法，值为${value}`);
      return value;
    },
    set(newValue) {
      if (newValue === value) return;
      obServer(newValue);
      value = newValue;
    },
  });
}

class ObServer {
  constructor(data) {
    //给data定义__ob__
    Object.defineProperty(data, "__ob__", {
      enumerable: false,
      value: this,
    });
    if (Array.isArray(data)) {
      data.__proto__ = ArrayMethods;
      this.observeArray(data);
    } else {
      this.walk(data);
    }
  }
  walk(data) {
    const keys = Object.keys(data);
    for (let i = 0; i < keys.length; i++) {
      // 对每个属性进行劫持
      const key = keys[i];
      const value = data[key];
      defineReactive(data, key, value);
    }
  }
  observeArray(data) {
    for (let i = 0; i < data.length; i++) {
      obServer(data[i]);
    }
  }
}
